package net.prasenjit.poc.httpclient;

import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.RequestContent;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * Created by PPurohit on 12/24/2014.
 */
public class HttpClientFactoryBean implements FactoryBean<HttpClient>, InitializingBean {

    private DefaultHttpClient httpClient;
    private ClientConnectionManager connectionManager;

    @Override
    public HttpClient getObject() throws Exception {
        return httpClient;
    }

    @Override
    public Class<?> getObjectType() {
        return HttpClient.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (null == connectionManager){
            httpClient = new DefaultHttpClient();
        }else {
            httpClient = new DefaultHttpClient(connectionManager);
        }
        RequestContent contentInterceptor = new RequestContent(true);
        httpClient.removeRequestInterceptorByClass(RequestContent.class);
        httpClient.addRequestInterceptor(contentInterceptor);
    }

    public void setConnectionManager(ClientConnectionManager connectionManager) {
        this.connectionManager = connectionManager;
    }
}
